define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'zhongzhuan/ec/tongji/index' + location.search,
                    add_url: 'zhongzhuan/ec/tongji/add',
                    edit_url: 'zhongzhuan/ec/tongji/edit',
                    del_url: 'zhongzhuan/ec/tongji/del',
                    multi_url: 'zhongzhuan/ec/tongji/multi',
                    import_url: 'zhongzhuan/ec/tongji/import',
                    export_url: 'zhongzhuan/ec/tongji/export',//导出路径
                    table: 'ec_tongji',
                }
            });

            var table = $("#table");
            
            table.on('post-common-search.bs.table', function (event, table) {

                // 以下2行代码是关键，是加载完表格后，把销售搜索空实例化成selectpage格式
                var form = $("form",table.$commonsearch);
               
                $("input[name='userinfo.deptId']",form).addClass("selectpage").data("source","zhongzhuan/ec/deparment/index").data("primaryKey","deptId").data("field","deptName");
                $("input[name='ecuser_id']",form).addClass("selectpage").data("source","zhongzhuan/ec/ecuser/index");
                
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
//                        {field: 'id', title: __('Id')},
                        {field: 'createtime', title: '日期',visible:false, operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'date', title: '日期',sortable:true,datetimeFormat:'YYYY-MM-DD',searchable:false, operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'ecuser_id', title: '员工',visible:false},
                        {field: 'userinfo.deptId', title: '所属部门',visible:false},
                        {field: 'deptinfo.deptName', title: '所属部门',searchable:false},
                        {field: 'userinfo.name', title: '员工',searchable:false},
                        {field: 'by_assign', title: __('By_assign'),searchable:false,sortable:true},
                        {field: 'by_auto_assign', title: __('By_auto_assign'),searchable:false,sortable:true},
                        {field: 'by_shoudong_assign', title: __('By_shoudong_assign'),searchable:false,sortable:true},
                        {field: 'fy_assign', title: __('Fy_assign'),searchable:false,sortable:true},
                        {field: 'fy_auto_assign', title: __('Fy_auto_assign'),searchable:false,sortable:true},
                        {field: 'fy_shoudong_assign', title: __('Fy_shoudong_assign'),searchable:false,sortable:true},
                        {field: 'assign_count', title: '合计',searchable:false,sortable:true},
                        
//                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
//                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            table.on('post-header.bs.table', function () {
                let totalNum =0 ;let by_assignNum = 0;let by_auto_assignNum = 0;
                 let by_shoudong_assignNum =0 ;let fy_assignNum = 0;let fy_auto_assignNum = 0;
                  let fy_shoudong_assignNum =0 ;
                let data = table.bootstrapTable('getData');
                for (let i = 0; i < data.length; i++) {
                    by_assignNum += parseFloat(data[i].by_assign);
                    by_auto_assignNum += parseFloat(data[i].by_auto_assign);
                    by_shoudong_assignNum += parseFloat(data[i].by_shoudong_assign);
                   
                    fy_assignNum += parseFloat(data[i].fy_assign);
                    fy_auto_assignNum += parseFloat(data[i].fy_auto_assign);
                    fy_shoudong_assignNum += parseFloat(data[i].fy_shoudong_assign);
                    
                    totalNum += parseFloat(data[i].assign_count);
                }
//                // 创建合计行
                let totalRow = '<tr id="total">' +
                         '<td style="text-align: center; vertical-align: middle; ">' + '</td>' +
                          '<td style="text-align: center; vertical-align: middle; ">' +  '</td>' +
                           '<td style="text-align: center; vertical-align: middle; ">' +  '</td>' +
                    '<td style="text-align: center; vertical-align: middle; " >合计:</td>' + // 空列，保持与其他列对齐
            
                    '<td style="text-align: center; vertical-align: middle; ">' + by_assignNum + '</td>' +
                    '<td style="text-align: center; vertical-align: middle; ">' + by_auto_assignNum + '</td>' +
                    '<td style="text-align: center; vertical-align: middle; ">' + by_shoudong_assignNum + '</td>' +
                     
                    '<td style="text-align: center; vertical-align: middle; ">' + fy_assignNum + '</td>' +
                    '<td style="text-align: center; vertical-align: middle; ">' + fy_auto_assignNum + '</td>' +
                    '<td style="text-align: center; vertical-align: middle; ">' + fy_shoudong_assignNum + '</td>' +
                    '<td style="text-align: center; vertical-align: middle; ">' + totalNum + '</td>' +
                    '</tr>';
            

                // 插入合计行到表格底部
                table.find('tbody').append(totalRow);
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            $(document).on("click", ".btn-export", function () {
                var ids = Table.api.selectedids(table);
                var page = table.bootstrapTable('getData');
                var all = table.bootstrapTable('getOptions').totalRows;
                console.log(ids, page, all);
                Layer.confirm("请选择导出的选项<form action='" + Fast.api.fixurl($.fn.bootstrapTable.defaults.extend.export_url) + "' method='post' target='_blank'><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'></form>", {
                    title: '导出数据',
                    btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
                    success: function (layero, index) {
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                    },
                    yes: function (index, layero) {
                        submitForm(ids.join(","), layero);
                        return false;
                    },
                    btn2: function (index, layero) {
                        var ids = [];
                        $.each(page, function (i, j) {
                            ids.push(j.id);
                        });
                        submitForm(ids.join(","), layero);
                        return false;
                    },
                    btn3: function (index, layero) {
                        submitForm("all", layero);
                        return false;
                    }
                })
            });
            var submitForm = function (ids, layero) {
                var options = table.bootstrapTable('getOptions');
                console.log(options);
                var columns = [];
                $.each(options.columns[0], function (i, j) {
                    if (j.field && !j.checkbox && j.visible && j.field != 'operate') {
                        columns.push(j.field);
                    }
                });
                var search = options.queryParams({});
                $("input[name=search]", layero).val(options.searchText);
                $("input[name=ids]", layero).val(ids);
                $("input[name=filter]", layero).val(search.filter);
                $("input[name=op]", layero).val(search.op);
                $("input[name=columns]", layero).val(columns.join(','));
                $("form", layero).submit();
            };
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
